<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class PlanResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        $data = [
            'id' => $this->id,
            'title' => $this->title,
            'cover' => $this->cover,
            'cover_url' => $this->coverUrl(),
            'status' => $this->status,
            'address' => $this->address,
            'description' => $this->description,
            'date' => $this->date->format('Y-m-d H:i:s'),
            'users' => $this->users->map(function ($user) {
                return [
                    'id' => $user->id,
                    'name' => $user->name,
                    'avatar' => $user->avatar(),
                ];
            }),
            'uids' => $this->users->map(function ($user) {
                return $user->id;
            }),
            'can_update' => $request->user()->can('update', [$this->resource, 'plans.update']),
            'can_delete' => $request->user()->can('update', [$this->resource, 'plans.destroy']),
            'can_upload' => $request->user()->can('update', [$this->resource, 'photos.store']),
            'can_view' => $request->user()->can('view', [$this->resource, 'plans.show']),
            'can_toggle' => $request->user()->can('toggle', [$this->resource, 'photos.toggle']),
            'is_owner' => $request->user()->id === $this->user_id,
            'created_at' => $this->created_at->format('Y-m-d H:i:s'),
            'updated_at' => $this->updated_at->format('Y-m-d H:i:s'),
        ];

        // 拍摄详情增加 photos 图片列表字段
        if ($request->route()->getName() === 'plans.show') {
            $data['photos'] = $this->photoes->map(function ($photo) {
                return new PhotoResource($photo);
            });
        }

        return $data;
    }
}
